package com.atguigu.guilimall.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.EsConstant;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.guilimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.guilimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @DESCRIPTION:
 * @Author: zr
 * @DATE: 2022/11/20 22:59
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 将数据保存到ES
        //  1、给ES中建立索引 product 建立好映射关系
        BulkRequest bulkRequest = new BulkRequest();
        // 2、给ES中保存这些数据 批量保存
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 设置索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置唯一Id
            indexRequest.id(skuEsModel.getSkuId().toString());
            String skuJson = JSON.toJSONString(skuEsModel);
            // 设置内容 为JSON  并设置格式
            indexRequest.source(skuJson, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        // 有失败返回True  这里有坑 返回的是否有错误
        boolean hasFailures = bulk.hasFailures();
        // 将相应结果返回为流 并返回相应的Id
        List<String> idS = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.error("商品上架错误:{}", idS);
        return hasFailures;
    }
}
